<template>
  <create-frame title="修改发货订单" @submit="onSubmit">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-suffix=":" inline
      label-position="right">
      <el-form-item class="form-item" label="创建人">
        <el-input disabled :model-value="detail?.cuser"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="创建时间">
        <el-input disabled :model-value="detail?.ctime"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="订单编号" prop="orderNumber">
        <el-input disabled v-model="form.orderNumber"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="PO订单号" prop="poNumber">
        <el-input v-model="form.poNumber"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="采购主体" prop="purchaseCompanyCode">
        <zw-select :data="purchaseCompanyList" label-key="name" value-key="code"
          v-model:value="form.purchaseCompanyCode" v-model:label="form.purchaseCompany"></zw-select>
      </el-form-item>
      <el-form-item class="form-item" label="联系人" prop="contactor">
        <el-input v-model="form.contactor"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="联系电话" prop="telephone">
        <el-input v-model="form.telephone"></el-input>
      </el-form-item>
      <el-form-item class="form-item-line" label="联系地址" prop="address">
        <el-input v-model="form.address"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="物流公司" prop="logisticsCompanyCode">
        <zw-select :data="logisticsCompanyList" label-key="name" value-key="code"
          v-model:value="form.logisticsCompanyCode" v-model:label="form.logisticsCompany"></zw-select>
      </el-form-item>
      <el-form-item class="form-item" label="物流单号" prop="logisticsNumber">
        <el-input v-model="form.logisticsNumber"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="出货日期" prop="shippingDate">
        <zw-date-picker v-model="form.shippingDate" />
      </el-form-item>
    </el-form>
    <create-list-frame :show-index-column="false" :inner-control="true" title="物料" :columns="columns"
      :table-data="tableData" :total="tableData.length">
      <template #buttons>
        <el-button type="primary" @click="currentMaterial = null; createMaterialViewVisible = true;">添加物料</el-button>
        <create-material-view :visible="createMaterialViewVisible" :data="currentMaterial"
          @save="onCreateMaterialViewSaved" @close="createMaterialViewVisible = false"></create-material-view>
      </template>
      <template #operations="row">
        <el-button link type="primary"
          @click="currentMaterial = row.value; createMaterialViewVisible = true;">编辑</el-button>
        <el-button link type="danger" @click="onDeleteMaterial(row)">删除</el-button>
      </template>
    </create-list-frame>
  </create-frame>
</template>
<script lang="ts" setup>
import CreateFrame from '@/components/CeateFrame/CreateFrame.vue';
import ApiTree from '@/server/api-tree';
import { DictTypeEnum, type DictVO } from '@/server/dict/types';
import { type ShippingVO, type ShippingMaterialVO, type ShippingDTO } from '@/server/shipping/types';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { onMounted, reactive, ref, useTemplateRef } from 'vue';
import ZwDatePicker from '@/components/Form/ZwDatePicker.vue';
import CreateListFrame from '@/components/CeateFrame/CreateListFrame.vue';
import type { ColumnType } from '@/components/types';
import CreateMaterialView from './CreateMaterialView.vue';
import ZwSelect from '@/components/Form/ZwSelect.vue';
import ElConfirm from '@/components/ElConfirm';
import { useRoute } from 'vue-router';
import emits, { EventEnum } from '@/plugins/emits';
import StrUitl from '@/plugins/str';
import WinUtil, { WinNameRecord } from '@/plugins/window';

const route = useRoute();
const guid = ref<string>(route.query.guid?.toString() || "");

const form = ref<ShippingVO>({
  guid: "",
  orderNumber: "",
  poNumber: "",
  /**
   * 采购主体编码
   */
  purchaseCompanyCode: "",
  /**
   * 采购主体名称
   */
  purchaseCompany: "",
  contactor: "",
  telephone: "",
  address: "",
  /**
   * 物流公司编码
   */
  logisticsCompanyCode: "",
  /**
   * 物流公司名称
   */
  logisticsCompany: "",
  /**
   * 物流编号
   */
  logisticsNumber: "",
  /**
   * 出货日期
   */
  shippingDate: "",
  shippingMaterials: []
});
const fomrRef = useTemplateRef<FormInstance>('formRef');
const shippingMaterialsValidator = () => {
  if (!form.value.shippingMaterials) {
    return "物料数据不能为空";
  }
  if (form.value.shippingMaterials.length === 0) {
    return "物料数据不能为空";
  }
  const errorMsg = [] as string[];
  form.value.shippingMaterials.forEach((x, index) => {
    const val = x as ShippingMaterialVO;
    if (!val.materialCode) {
      errorMsg.push(`第${index + 1}行数据填写不完整！`);
    }
  })
  if (errorMsg.length > 0) {
    return errorMsg.join(";");
  }
  return "";
}
const rules = reactive<FormRules<ShippingVO>>({
  orderNumber: [{ required: true, message: "订单编号不能为空" }],
  poNumber: [{ required: true, message: "PO订单号不能为空" }],
  purchaseCompanyCode: [{ required: true, message: "采购主体不能为空" }],
  contactor: [{ required: true, message: "联系人不能为空" }],
  telephone: [{ required: true, message: "联系电话不能为空" }],
  address: [{ required: true, message: "联系地址不能为空" }],
  logisticsCompanyCode: [{ required: true, message: "物流公司不能为空" }],
  logisticsNumber: [{ required: true, message: "物流单号不能为空" }],
  shippingDate: [{ required: true, message: "出货日期不能为空" }],
  shippingMaterials: [{ required: true, validator: shippingMaterialsValidator }]
})
/** 获取采购主体 */
const purchaseCompanyList = ref<DictVO[]>([]);
const getPurchaseCompanyList = async () => {
  const { success, data } = await ApiTree.dict.list(DictTypeEnum.PURCHASE_COMPANY, true);
  if (success) {
    purchaseCompanyList.value = data;
  }
}
/** 获取物流公司 */
const logisticsCompanyList = ref<DictVO[]>([])
const getLogisticsCompanyList = async () => {
  const { success, data } = await ApiTree.dict.list(DictTypeEnum.LOGISTICS_COMPANY, true);
  if (success) {
    logisticsCompanyList.value = data;
  }
}
/** 物料表格 */
const columns = [
  { prop: "id", colName: "序号", width: 0 },
  { prop: "material", colName: "物料名称", width: 0 },
  { prop: "count", colName: "数量", width: 0 },
  { prop: "sn", colName: "SN", width: 0 },
] as ColumnType[];
const tableData = ref<(ShippingMaterialVO & { guid: string, id: number })[]>([])
const createMaterialViewVisible = ref(false)
const currentMaterial = ref<(ShippingMaterialVO & { guid: string }) | null>(null);

const onCreateMaterialViewSaved = (data: ShippingMaterialVO & { guid: string }) => {
  // 拆分一下sn
  const snList = data.sn ? StrUitl.split(data.sn, "\n", true, true) : [];
  // 检查拆分后的sn，是否存在重复项
  if (snList.length > 0) {
    const existsSn = snList.filter(sn => tableData.value.some(x => x.sn === sn));
    if (existsSn.length > 0) {
      ElMessage.error(`以下SN已经存在：${existsSn.join(",")}`);
      return;
    }
  }
  // 输入了多少数量，就生成多少行，每行的数量是1
  const count = data.count <= 0 ? snList.length : data.count;
  if (count === 0) {
    ElMessage.error(`数量和SN不能同时为0或空`);
    return;
  }
  // 查询一下是否是点了某一行的编辑
  const index = tableData.value.findIndex(x => x.guid === data.guid);
  if (index >= 0) {
    // 如果是编辑，则删除这一行数据
    tableData.value.splice(index, 1);
  }
  // 添加新数据
  for (let index = 0; index < count; index++) {
    tableData.value.push({
      id: index + 1,
      guid: StrUitl.random(8),
      count: 1,
      sn: snList.length > index ? StrUitl.trim(snList[index], '"') : "",
      material: data.material,
      materialCode: data.materialCode
    });
  }
  createMaterialViewVisible.value = false;
}
const onDeleteMaterial = (row: { value: ShippingMaterialVO & { guid: string } }) => {
  const m = row.value;
  ElConfirm(`确定要删除物料【${m.sn}】吗？`).then(() => {
    const index = tableData.value.findIndex(x => x.guid === m.guid);
    tableData.value.splice(index, 1);
  }).catch();
}
/** 提交表单 */
const onSubmit = () => {
  fomrRef.value?.validate(async (valid) => {
    if (valid) {
      form.value.shippingMaterials = tableData.value;
      const err = shippingMaterialsValidator()
      if (err !== "") {
        ElMessage.error(err);
        return;
      }
      const { success, msg } = await ApiTree.shipping.update(form.value);
      if (success) {
        ElMessage.success(msg);
        setTimeout(() => {
          emits.triggerOwner(EventEnum.TABLE_RELOAD);
          WinUtil.open("/shipping/detail?guid=" + guid.value, WinNameRecord.SHIPPING_DETAIL, guid.value).close();
        }, 300);
      }
    }
  })
}

/** 获取明细 */
const detail = ref<ShippingDTO>();
const getDetail = async () => {
  const { success, data } = await ApiTree.shipping.getDetail(guid.value);
  if (success) {
    detail.value = data.shipping;
    form.value = {
      ...data.shipping,
      shippingMaterials: data.shippingMaterials
    }
    tableData.value = data.shippingMaterials.map((x, index) => {
      return {
        ...x,
        id: index + 1
      };
    });
  }
}
onMounted(() => {
  if (!guid.value) {
    ElMessage.error("缺少关键参数！");
    setTimeout(() => {
      window.close();
    }, 200);
    return;
  }
  getDetail();
  getPurchaseCompanyList();
  getLogisticsCompanyList();

})
</script>
<style lang="scss" scope>
.form-item {
  width: calc(100% / 2 - 32px);

  &-line {
    width: calc(100% - 32px);
  }
}
</style>
